import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Inject,
  Logger,
  Post,
  Req,
  Request,
  Res,
  Session,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { VerificationCodeService } from 'src/component/code/verification-code.service';
import { ToolsService } from 'src/utils/tools.service';
import { AuthService } from './auth.service';
import { ApiBody, ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { LoginDTO } from './dto/login.dto';
// import { CurrentUser } from './auth.decorator';

@ApiTags('权限模块')  
@Controller('auth')
export class AuthController {

  private readonly logger = new Logger(AuthController.name);


  @Inject()
  private readonly verificationCodeService: VerificationCodeService;


  constructor(
    private readonly authService: AuthService,
    ) {}


  @ApiOperation({ summary: '获取验证码', description: '获取验证码'})  
  @Get('authcode') //当请求该接口时，返回一张随机图片验证码
  async getCode(@Req() req, @Res() res,@Session() session) {
  
    const svgCaptcha = await this.verificationCodeService.captche(); //创建验证码
    session.code = svgCaptcha.text; //使用session保存验证，用于登陆时验证
    this.logger.debug(`session.code:${ JSON.stringify(session)}}`);
    this.verificationCodeService.saveCode(svgCaptcha.text);
    // 允许跨域
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.type('image/svg+xml'); //指定返回的类型
    res.send(svgCaptcha.data); //给页面返回一张图片
  }

  // 登录测试
  @UseGuards(AuthGuard('local')) //本地策略，传递local，执行local里面的validate方法
  @Post('login')
  @ApiOperation({ summary: '登录', description: '登录'})  
  @ApiBody({ type: LoginDTO , description: '输入用户名和密码' })
  async login(@Req() req, @Body()  body : LoginDTO, @Session() session) {
    //验证验证码，由前端传递过来
    const { code } = body;
    if (!code) {
     return ToolsService.fail('验证码不能为空');
    }
    this.logger.debug(`验证码:${code}`);
    this.logger.debug(`session.code:${ JSON.stringify(session.code)}`);

    if (code?.toUpperCase() === session.code?.toUpperCase()) {
      this.logger.debug(`验证码通过`);
    } else {
      ToolsService.fail('验证码错误');
    }
    //通过req可以获取到validate方法返回的user，传递给login，登陆
    return this.authService.login(req.user);
  }

  // 测试登录后才可访问的接口，在需要的地方使用守卫，可保证必须携带token才能访问
  @Get('user')
  @ApiOperation({ summary: '获取用户信息', description: '获取用户信息'})  
  @UseGuards(AuthGuard('jwt')) //jwt策略，身份鉴权
  //通过req获取到被验证后的user，也可以使用装饰器
  getProfile(@Request() req) {
    console.log('req', req.user);
    return req.user;
  }
}
